<template>
	<view class="index-container">
		<!-- 欢迎banner -->
		<view class="welcome-banner">
			<view class="user-info">
				<text class="greeting">{{ greeting }}</text>
				<text class="username">{{ userInfo ? userInfo.nickname || userInfo.realName : '未登录' }}</text>
			</view>
			<view class="date-info">
				<text class="time">{{ currentTime }}</text>
				<text class="date">{{ currentDate }}</text>
			</view>
		</view>
		
		<!-- 通知区域 -->
		<view class="notice-section">
			<view class="section-header">
				<text class="title">最新公告</text>
			</view>
			<view v-if="latestNotice" class="notice-content">
				<view class="notice-title">{{ latestNotice.title }}</view>
				<view class="notice-text">{{ latestNotice.content }}</view>
				<view class="notice-time">{{ formatTime(latestNotice.createTime) }}</view>
			</view>
			<view v-else class="empty-notice">
				暂无公告
			</view>
		</view>
		
		<!-- 考勤区域 -->
		<view class="attendance-section">
			<view class="section-header">
				<text class="title">今日考勤</text>
				<text class="subtitle">{{ todayAttendance ? '已完成签到' : '未签到' }}</text>
			</view>
			
			<!-- 打卡入口 -->
			<view class="attendance-actions">
				<button class="clock-btn" @tap="navigateToClock">
					<text class="btn-text">位置打卡</text>
					<text class="btn-desc">上/下班打卡</text>
				</button>
			</view>
		</view>
		
		<!-- 考勤弹窗 -->
		<uni-popup ref="popup" type="bottom">
			<view class="attendance-popup">
				<view class="popup-header">
					<text class="title">考勤打卡</text>
					<text class="close" @tap="closePopup">×</text>
				</view>
				
				<view class="attendance-form">
					<!-- 考勤类型选择 -->
					<view class="form-item">
						<text class="label">考勤类型</text>
						<view class="type-group">
							<view 
								v-for="(type, index) in attendanceTypes" 
								:key="index"
								class="type-item"
								:class="{ 'active': attendanceForm.type === type.value }"
								@tap="selectType(type.value)"
							>
								{{ type.label }}
							</view>
						</view>
					</view>
					
					<!-- 工作时长(仅小时工显示) -->
					<view class="form-item" v-if="attendanceForm.type === 3">
						<text class="label">工作时长(小时)</text>
						<input 
							type="digit" 
							v-model="attendanceForm.workHours"
							class="input"
							placeholder="请输入工作时长"
						/>
					</view>
					
					<!-- 备注信息 -->
					<view class="form-item">
						<text class="label">备注信息</text>
						<textarea 
							v-model="attendanceForm.remark"
							class="textarea"
							placeholder="请输入备注信息(选填)"
						/>
					</view>
					
					<!-- 提交按钮 -->
					<button 
						class="submit-btn"
						:loading="submitting"
						:disabled="submitting"
						@tap="handleSubmit"
					>
						{{ submitting ? '提交中...' : '确认打卡' }}
					</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import dayjs from 'dayjs'
import noticeApi from '@/api/notice'
import attendance from '@/api/attendance'

// 用户信息
const userInfo = ref(null)

// 当前时间
const currentTime = ref('')
const currentDate = ref('')
const greeting = ref('')

// 最新通知
const latestNotice = ref(null)

// 今日考勤记录
const todayAttendance = ref(null)

// 考勤类型选项
const attendanceTypes = [
	{ label: '全天班', value: 1 },
	{ label: '半天班', value: 2 },
	{ label: '小时工', value: 3 }
]

// 考勤表单
const attendanceForm = ref({
	type: 1,
	workHours: '',
	remark: '',
	date: dayjs().format('YYYY-MM-DD')
})

// 加载状态
const submitting = ref(false)

// popup引用
const popup = ref(null)

// 更新时间
function updateTime() {
	const now = dayjs()
	currentTime.value = now.format('HH:mm:ss')
	currentDate.value = now.format('YYYY年MM月DD日 dddd')
	
	const hour = now.hour()
	if (hour < 6) {
		greeting.value = '凌晨好'
	} else if (hour < 9) {
		greeting.value = '早上好'
	} else if (hour < 12) {
		greeting.value = '上午好'
	} else if (hour < 14) {
		greeting.value = '中午好'
	} else if (hour < 17) {
		greeting.value = '下午好'
	} else if (hour < 19) {
		greeting.value = '傍晚好'
	} else {
		greeting.value = '晚上好'
	}
}

// 获取用户信息
function getUserInfo() {
	const info = uni.getStorageSync('userInfo')
	if (info) {
		userInfo.value = JSON.parse(info)
	}
}

// 格式化时间
function formatTime(time) {
	return dayjs(time).format('YYYY-MM-DD HH:mm')
}

// 获取考勤类型文本
function getAttendanceTypeText(type) {
	const typeObj = attendanceTypes.find(t => t.value === type)
	return typeObj ? typeObj.label : ''
}

// 获取最新通知
async function getLatestNotice() {
	try {
		const data = await noticeApi.getLatest()
		latestNotice.value = data
	} catch (error) {
		console.error('获取通知失败:', error)
	}
}

// 获取今日考勤
async function getTodayAttendance() {
	try {
		const data = await attendance.getTodayAttendance()
		todayAttendance.value = data
	} catch (error) {
		console.error('获取考勤失败:', error)
	}
}

// 选择考勤类型
function selectType(type) {
	attendanceForm.value.type = type
	// 切换类型时清空工时
	if (type !== 3) {
		attendanceForm.value.workHours = ''
	}
}

// 显示考勤弹窗
function showAttendancePopup() {
	// 如果 todayAttendance 有值，说明已签到，则不弹窗
	if (todayAttendance.value) return
	popup.value.open()
}
// 关闭考勤弹窗
function closePopup() {
	popup.value.close()
}

// 快速签到(点击按钮)
async function handleQuickAttendance() {
	if (todayAttendance.value) return
	
	try {
		submitting.value = true
		await attendance.addAttendance({
			type: 1, // 默认全天班
			date: dayjs().format('YYYY-MM-DD')
		})
		
		uni.showToast({
			title: '签到成功',
			icon: 'success'
		})
		
		// 重新获取今日考勤
		await getTodayAttendance()
	} catch (error) {
		uni.showToast({
			title: error.message || '签到失败',
			icon: 'none'
		})
	} finally {
		submitting.value = false
	}
}

// 提交考勤(弹窗)
async function handleSubmit() {
	// 表单验证
	if (attendanceForm.value.type === 3) {
		if (!attendanceForm.value.workHours) {
			uni.showToast({
				title: '请输入工作时长',
				icon: 'none'
			})
			return
		}
		
		const hours = Number(attendanceForm.value.workHours)
		if (hours <= 0) {
			uni.showToast({
				title: '工作时长必须大于0',
				icon: 'none'
			})
			return
		}
		
		if (hours > 15) {
			uni.showToast({
				title: '工作时长不能超过15小时',
				icon: 'none'
			})
			return
		}
	}
	
	try {
		submitting.value = true
		await attendance.addAttendance(attendanceForm.value)
		
		uni.showToast({
			title: '签到成功',
			icon: 'success'
		})
		
		// 重新获取今日考勤
		await getTodayAttendance()
		// 关闭弹窗
		closePopup()
		// 重置表单
		attendanceForm.value = {
			type: 1,
			workHours: '',
			remark: '',
			date: dayjs().format('YYYY-MM-DD')
		}
	} catch (error) {
		uni.showToast({
			title: error.message || '签到失败',
			icon: 'none'
		})
	} finally {
		submitting.value = false
	}
}

// 跳转到打卡页面
function navigateToClock() {
	uni.navigateTo({
		url: '/pages/clock/index'
	})
}

// 页面加载
onMounted(() => {
	getUserInfo()
	updateTime()
	// 每秒更新时间
	setInterval(updateTime, 1000)
})

// 页面显示
onShow(async () => {
	// 每次显示页面时重新获取数据
	await Promise.all([
		getLatestNotice(),
		getTodayAttendance()
	])
})
</script>

<style lang="scss">
.index-container {
	min-height: 100vh;
	padding: 30rpx;
	background-color: #f5f5f5;
	
	.welcome-banner {
		background: linear-gradient(135deg, #1296db, #6bc6ff);
		border-radius: 20rpx;
		padding: 40rpx 30rpx;
		margin-bottom: 30rpx;
		color: #fff;
		
		.user-info {
			margin-bottom: 20rpx;
			
			.greeting {
				font-size: 32rpx;
				margin-right: 16rpx;
			}
			
			.username {
				font-size: 36rpx;
				font-weight: bold;
			}
		}
		
		.date-info {
			.time {
				font-size: 48rpx;
				font-weight: bold;
				margin-bottom: 8rpx;
				display: block;
			}
			
			.date {
				font-size: 24rpx;
				opacity: 0.8;
			}
		}
	}
	
	.section-header {
		margin-bottom: 20rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		
		.title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
		}
		
		.subtitle {
			font-size: 24rpx;
			color: #666;
		}
	}
	
	.notice-section {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 30rpx;
		margin-bottom: 30rpx;
		
		.notice-content {
			.notice-title {
				font-size: 30rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 16rpx;
			}
			
			.notice-text {
				font-size: 28rpx;
				color: #666;
				line-height: 1.6;
				margin-bottom: 16rpx;
			}
			
			.notice-time {
				font-size: 24rpx;
				color: #999;
			}
		}
		
		.empty-notice {
			text-align: center;
			color: #999;
			font-size: 28rpx;
			padding: 40rpx 0;
		}
	}
	
	.attendance-section {
		background-color: #fff;
		border-radius: 20rpx;
		padding: 30rpx;
		
		.attendance-actions {
			display: flex;
			justify-content: center;
			padding: 40rpx 0;
			
			.clock-btn {
				width: 200rpx;
				height: 200rpx;
				border-radius: 50%;
				background: linear-gradient(135deg, #1296db, #6bc6ff);
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				box-shadow: 0 8rpx 16rpx rgba(18, 150, 219, 0.2);
				transition: all 0.3s;
				
				.btn-text {
					color: #fff;
					font-size: 32rpx;
					font-weight: bold;
					margin-bottom: 8rpx;
				}
				
				.btn-desc {
					color: rgba(255, 255, 255, 0.8);
					font-size: 24rpx;
				}
			}
		}
	}
	
	.attendance-popup {
		background-color: #fff;
		border-radius: 30rpx 30rpx 0 0;
		padding: 30rpx;
		
		.popup-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 40rpx;
			
			.title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}
			
			.close {
				font-size: 40rpx;
				color: #999;
				padding: 10rpx;
			}
		}
		
		.attendance-form {
			.form-item {
				margin-bottom: 30rpx;
				
				.label {
					font-size: 28rpx;
					color: #666;
					margin-bottom: 16rpx;
					display: block;
				}
				
				.type-group {
					display: flex;
					gap: 20rpx;
					
					.type-item {
						flex: 1;
						height: 80rpx;
						border-radius: 12rpx;
						border: 2rpx solid #ddd;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 28rpx;
						color: #666;
						transition: all 0.3s;
						
						&.active {
							background-color: #1296db;
							border-color: #1296db;
							color: #fff;
						}
					}
				}
				
				.input {
					height: 80rpx;
					border-radius: 12rpx;
					border: 2rpx solid #ddd;
					padding: 0 20rpx;
					font-size: 28rpx;
				}
				
				.textarea {
					width: 100%;
					height: 160rpx;
					border-radius: 12rpx;
					border: 2rpx solid #ddd;
					padding: 20rpx;
					font-size: 28rpx;
				}
			}
			
			.submit-btn {
				background: linear-gradient(135deg, #1296db, #6bc6ff);
				color: #fff;
				height: 88rpx;
				line-height: 88rpx;
				border-radius: 44rpx;
				font-size: 32rpx;
				font-weight: bold;
				margin-top: 40rpx;
				
				&[disabled] {
					opacity: 0.7;
				}
			}
		}
	}
}
</style>
